package com.example.utils;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.util.Objects;

public class EntityToXmlConverter {
    public static String convertToXmlString(Object entity) {
        StringBuilder xmlBuilder = new StringBuilder();
        xmlBuilder.append("<").append(entity.getClass().getSimpleName()).append(">");

        Field[] fields = entity.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object fieldValue;
            try {
                fieldValue = field.get(entity);
            } catch (IllegalAccessException e) {
                fieldValue = null;
            }

            if (Objects.nonNull(fieldValue)) {
                xmlBuilder.append("  <").append(fieldName).append(">")
                        .append(fieldValue.toString())
                        .append("</").append(fieldName).append(">");
            }else{
                xmlBuilder.append("  <").append(fieldName).append(">")
                        .append("</").append(fieldName).append(">");
            }
        }

        xmlBuilder.append("</").append(entity.getClass().getSimpleName()).append(">");
        String xmlString = xmlBuilder.toString();

        // 格式化XML字符串
        return formatXml(xmlString);
    }

    private static String formatXml(String xmlString) {
        try {
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

            // 创建源和目标
            Source xmlInput = new StreamSource(new StringReader(xmlString));
            StringWriter stringWriter = new StringWriter();
            StreamResult xmlOutput = new StreamResult(stringWriter);

            // 执行转换
            transformer.transform(xmlInput, xmlOutput);

            String formattedXmlString = xmlOutput.getWriter().toString();

            // 移除空白行
            formattedXmlString = formattedXmlString.replaceAll("(?m)^[ \t]*\r?\n", "");

            return formattedXmlString;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return xmlString; // 返回原始的XML字符串，如果格式化失败
    }

}